package build_util;


import com.ebay.ice.api.ArrayOfDeployObj;
import com.ebay.ice.api.AuthObj;
import com.ebay.ice.api.BuildObj;
import com.ebay.ice.api.DeployObj;
import com.ebay.ice.api.ProjectHelperProxy;
import com.ebay.ice.api.ProjectObj;
import com.ebay.ice.api.QueryHelperProxy;
import com.ebay.ice.api.RequestHelperProxy;
import com.ebay.ice.api.RequestObj;
import com.ebay.ice.api.ResultObj;
import com.ebay.ice.api.TargetSetObj;
import com.ebay.ice.api.TargetSetResultObj;
import com.ebay.ice.api.TaskDetailObj;

import env.ConstDef;
import env.GlobalEnv;

public class APITestLegacy {

	private AuthObj authObj;
	private RequestHelperProxy requestHelper;
	ProjectHelperProxy projHelper;
	QueryHelperProxy queryHelper;

	private final static String apiKeyUserName = "iceteam";	// iceteam
	private final static String apiKeyPassword = "iceteam";	// iceteam

	public APITestLegacy() {
		authObj = new AuthObj();
		// user name and password registered in production db
		authObj.setPassword(apiKeyPassword); 
		authObj.setUserName(apiKeyUserName);
		
		// The following two lines pointing to the ICE web service end point
//		String serviceEndPoint_RequestHelper = "http://iceapi.corp.ebay.com/ICEWebServices/services/RequestHelper";
//		String serviceEndPoint_ProjectHelper = "http://iceapi.corp.ebay.com/ICEWebServices/services/ProjectHelper";
//		String serviceEndPoint_QueryHelper = "http://iceapi.corp.ebay.com/ICEWebServices/services/QueryHelper";
		//String serviceEndPoint_RequestHelper = "http://iceapi.corp.ebay.com/ICEWebServices/services/RequestHelper";
//        String serviceEndPoint_ProjectHelper = "http://iceapi.corp.ebay.com/ICEWebServices/services/ProjectHelper";
//        String serviceEndPoint_QueryHelper =   "http://iceapi.corp.ebay.com:8080/ICEWebServices/services/QueryHelper";
		//String serviceEndPoint_RequestHelper = "http://icepanel05.corp.ebay.com:8080/ICEWebServices/services/RequestHelper";
		//String serviceEndPoint_ProjectHelper = "http://icepanel05.corp.ebay.com:8080/ICEWebServices/services/ProjectHelper";
		//String serviceEndPoint_QueryHelper = "http://icepanel05.corp.ebay.com:8080/ICEWebServices/services/QueryHelper";
//		String serviceEndPoint_RequestHelper = "http://SJC-VTS-363.corp.ebay.com:8080/ICEWebServices/services/RequestHelper";
//		String serviceEndPoint_ProjectHelper = "http://SJC-VTS-363.corp.ebay.com:8080/ICEWebServices/services/ProjectHelper";
//		String serviceEndPoint_QueryHelper = "http://SJC-VTS-363.corp.ebay.com:8080/ICEWebServices/services/QueryHelper";
	
		requestHelper = new RequestHelperProxy(GlobalEnv.SERVICEENDPOINT_REQUESTHELPER);
		projHelper = new ProjectHelperProxy(GlobalEnv.SERVICEENDPOINT_PROJECTHELPER);
		queryHelper = new QueryHelperProxy(GlobalEnv.SERVICEENDPOINT_QUERYHELPER);
	}

	public ResultObj createRequest(int requestType, int poolType, int featureOrTrackerID, int[] targetSetids) {
		RequestObj request = new RequestObj();
		request.setCreator(GlobalEnv.getCreator());
		request.setRequestType(requestType);
		request.setName("ICEAPI_Test_Request");
		request.setScheduleInterval(-1); // no schedule, manually kick off
		request.setPoolType(poolType);
		
		if(targetSetids != null && targetSetids.length > 0){
			TargetSetObj[] ts = new TargetSetObj[targetSetids.length];
			for (int i = 0 ; i < ts.length; i++){
				ts[i] = new TargetSetObj();
				ts[i].setSetId(targetSetids[i]); 
			}
			request.setTargetSets(ts);
		}
		if(featureOrTrackerID > 0){
			switch (requestType) {
			case ConstDef.RequestTypeEnum_FEATURE:
				request.setFeatureId(featureOrTrackerID); // User must specify feature id
				break;
			case ConstDef.RequestTypeEnum_STAGING:
				request.setTrackerId(featureOrTrackerID);  // User must specify tracker id
				break;
			case ConstDef.RequestTypeEnum_CUSTOM:
				// do nothing for Custom request type
				break;
			default:
			}			
		}
		
		return requestHelper.addReq(request, authObj);
	}	

	public ResultObj addProject(String projName, int buildTypeID, int reqID, String configSpec, String loadRules, TaskDetailObj[] tasks, int locale,boolean autoDeploy) {
		ResultObj result;
		ProjectObj projObj = new ProjectObj();
		projObj.setName(projName);
		projObj.setBuildType(buildTypeID);
		projObj.setConfigSpec(configSpec);
		projObj.setLoadRules(loadRules);
		projObj.setTasks(tasks);
		projObj.setLocale(locale);
		projObj.setAutoDeploy(autoDeploy);
		result = projHelper.addProject(projObj, String.valueOf(reqID), authObj);
		if (!result.isSuccess()) {
			String errMsg = "Failed to add project to request: (request id = " + reqID
					+ ")\r\n";
			errMsg += "Message if any\r\n";
			errMsg += result.getError();
			System.out.println(errMsg);
		}
		return result;
	}

	
	public ResultObj addProject(String projName, int buildTypeID, int reqID, String configSpec, String loadRules, String taskParams, String deliverable, int locale, boolean autoDeploy) {
		ResultObj result;
		ProjectObj projObj = new ProjectObj();
		projObj.setName(projName);
		projObj.setBuildType(buildTypeID);
		if(deliverable != null && !deliverable.trim().equals("")){
			projObj.setDeliverable(deliverable);
		}		
		projObj.setConfigSpec(configSpec);
		projObj.setLoadRules(loadRules);
		projObj.setParam(taskParams);
		projObj.setAutoDeploy(autoDeploy);
		projObj.setLocale(locale);
		result = projHelper.addProject(projObj, String.valueOf(reqID), authObj);
		if (!result.isSuccess()) {
			String errMsg = "Failed to add project to request: (request id = " + reqID
					+ ")\r\n";
			errMsg += "Message if any\r\n";
			errMsg += result.getError();
			System.out.println(errMsg);
		}
		return result;

	}
	public ResultObj activate(int reqID) {
		ResultObj result;
		result = requestHelper.activate(String.valueOf(reqID), authObj);
		if (!result.isSuccess()) {
			String errMsg = "Failed to activate request with ID = " + reqID
					+ "\r\n";
			errMsg += "Message if any\r\n";
			errMsg += result.getError();
			System.out.println(errMsg);
		}
		return result;
	}

	public void getReq(int reqID) {
		RequestObj request;
		request = requestHelper.getReq(String.valueOf(reqID));
		if (request == null) {
			System.out.println("Failed get request data for request " + reqID);
			return;
		}
		System.out.println("Projects in this request:");
		ProjectObj[] projects = request.getProjects();
		if (projects == null || projects.length < 1) {
			System.out.println("No project found for this request!");
		} else {
			for (int i = 0; i < projects.length; i++) {
				String projName = projects[i].getName();
				System.out.println("Project Name : " + projName);
				TaskDetailObj[] taskDetails = projects[i].getTasks();
				if (taskDetails == null || taskDetails.length < 1) {
					System.out.println("No task detail found for project: "
							+ projName);
					continue;
				}
				for (TaskDetailObj taskDetail : taskDetails) {
					String taskName = taskDetail.getName();
					String[] paramNames = taskDetail.getParamNameArr();
					String[] paramValues = taskDetail.getParamValueArr();
					System.out.println("Task Name: " + taskName);
					if (paramNames == null || paramNames.length < 1) {
						System.out.println("No task parameter found for task: "
								+ taskName);
						continue;
					}
					for (int j = 0; j < paramNames.length; j++) {
						System.out.println("Parameter Name: " + paramNames[j]);
						System.out
								.println("Parameter Value: " + paramValues[j]);
					}
				}
			}
		}
	}

	public void doBuild(int reqID) {
		RequestObj request;
		request = requestHelper.getReq(String.valueOf(reqID));
		ProjectObj[] projects = request.getProjects();
		if (projects == null || projects.length < 1) {
			System.out.println("Cannot find any project for request " + reqID);
			return;
		}

		for (int i = 0; i < projects.length; i++) {
			ProjectObj aProj = projects[i];
			int projID = aProj.getProjId();
			ResultObj result;
			result = projHelper.doBuild(String.valueOf(projID), String
					.valueOf(reqID));
			if (result.isSuccess()) {
				System.out.println("Project  " + projID + " is in queue now");
			} else {
				System.out.println("Failed to put project  " + projID
						+ " to queue");
			}
		}
	}

	/**
	 * Before calling this API to do a feature deploy, the following things
	 * should be ready: 
	 * 1. A request is created.
	 * 2. Request pool type cannot be staging_tivoli or production. 
	 * 2. At least one project and its corresponding task parameters are created and added
	 * to the request
	 */
	public void doDeployFeature(int rbgID, DeployObj[] deployObjArray) {
		ArrayOfDeployObj arrOfDeployObj = new ArrayOfDeployObj();
		arrOfDeployObj.setDeployObj(deployObjArray);
		ResultObj rObj = requestHelper.doDeployFeature(String.valueOf(rbgID),
				arrOfDeployObj, authObj);
		if (rObj.isSuccess()) {
			System.out.println("Scheduled to Deploy...");
		} else {
			System.out.println("Failed scheduling to deploy..."
					+ rObj.getError());
		}
	}

	public void doDeployProduction(int rbgID) {

		ResultObj rObj = requestHelper.doDeployProd(String.valueOf(rbgID),
				null, authObj);
		if (rObj.isSuccess()) {
			System.out.println("Scheduled to Deploy...");
		} else {
			System.out.println("Failed scheduling to deploy..."
					+ rObj.getError());
		}
	}

	public void cancelDeployment(int reqID) {
		ResultObj result = requestHelper.cancelDeployment(reqID, authObj);
		if (result == null
				|| (result.getError() != null && result.getError().trim()
						.length() > 0)) {
			System.out.println("Failed to cancel deployment for request "
					+ reqID);
			System.out.println("Message if any:\r\n " + result.getError());
		} else {
			System.out.println("Deployment cancelled!");
		}
	}

	public void deActivate(int reqID) {
		ResultObj result = requestHelper.deactivate(String.valueOf(reqID),
				authObj);
		if (!result.isSuccess()) {
			System.out.println("Failed to deactivate request: " + reqID);
			System.out.println("Message if any: \r\n" + result.getError());
		} else {
			System.out.println("Request " + reqID + " is deactivated");
		}
	}
	
	public int getBuildStatus(int rbgID){
		ResultObj result = requestHelper.getBuildReqStatus(String.valueOf(rbgID));
		return result.getResultId();
		
	}
	

	
	public int getLatestBuildStatus(int reqID, int projectID){
		ResultObj result = projHelper.getAllBuildIds(String.valueOf(reqID), String.valueOf(projectID), authObj);
		int statusCode = -1;
		if(result.isSuccess()){
			Object[] buildIDs = result.getArrayData();
			
			if(buildIDs.length > 0){
				BuildObj build = projHelper.getBuild((String)buildIDs[0]);
				statusCode =  build.getStatus();
			}else{
				System.out.println("The project has no build yet.");
			}
		}else{
			System.out.println("Failed to get latest build for project " + projectID);
		}		
		return statusCode;
		
	}
	
	
	public int getLatestDeployStatus(int reqID, int projectID){
		ResultObj result = projHelper.getDeployStatus(String.valueOf(reqID), String.valueOf(projectID), authObj);
		if(result.isSuccess()){
			return result.getResultId();
		}else{
			System.out.println(result.getError());
			return -1;			
		}
	}
	
	public int updateProject2(int projectID, ProjectObj pObj){

		ResultObj result = projHelper.updateProject(Long.valueOf(projectID), pObj);
		if(result.isSuccess()){
			return result.getResultId();
		}else{
			System.out.println(result.getError());
			return -1;			
		}
		}
	
    public void testUpdateProject(){
    	int projectId = 44417;
    	ProjectObj pObjinit = projHelper.getProject(String.valueOf(projectId));
    	String[] taskNamesinit = pObjinit.getTaskName();
    	String[] taskParamsinit = pObjinit.getParameter();
    	int length = taskNamesinit.length;
    	
    	String[] taskNames = new String[length];
        String[] taskParams = new String[length];
        
        for (int i = 0;i<length;i++){
        	taskNames[i] = taskNamesinit[i];
        	taskParams[i] = taskParamsinit[i];
        }
        taskNames[0] = "ViewSync";
        taskParams[0] = "";
        
        taskNames[1] = "CCCreate";
        taskParams[1] = "-autotimestamp -viewdispatchmode -nomegajar";

        taskNames[2] = "BuildV4EAR";
        taskParams[2] = "-clean -antarg -Dglobal.delete.classes=true -runDependencyCheck xml -train e000 -locale core -pooltype feature -dbenv lpsan -deliverable bundled";
        
//      taskParams[length-1] = "-clean -antarg -Dglobal.delete.classes=true -runDependencyCheck xml -train e111 -locale core -pooltype feature -dbenv lpsan -deliverable bundled";

        
        String configSpec = "element * CHECKEDOUT\r\n"
    		+ "element * V3_DATASOURCE\r\n"
    		+ "element /entities/... /main/LATEST -time 13-June-11.22:47:40\r\n"
    		+ "element * .../e717_core_reroll/LATEST -time 13-June-11.22:47:40\r\n"
    		+ "mkbranch e717_core_reroll\r\n"
    		+ "element * E717_RELEASE_BASE\r\n"
    		+ "element * E717_CABOOSE_BASE\r\n"
    		+ "element * /main/0\r\n"
    		+ "end mkbranch e717_core_reroll";
    	
        ProjectObj pObj = new ProjectObj();
        pObj.setTaskName(taskNames);
        pObj.setParameter(taskParams);
        pObj.setProjId(projectId);
//        pObj.setConfigSpec(configSpec);
//        int pid = 44308;
        ResultObj result =projHelper.updateProject2(pObj);
//        ResultObj result =projHelper.updateProject2(pid, pObj);
        if(!result.isSuccess()){
             System.out.println(result.getError());
        }
    }
    
	
    public void testGetProject(){
    	ProjectObj pObj = new ProjectObj();
    	int projectId = 1978840;
//    	pObj = projHelper.getProject(String.valueOf(projectId), String.valueOf(16783));
    	pObj = projHelper.getProject(String.valueOf(projectId));
    	String name[] = pObj.getTaskName();;
    	String para [] = pObj.getParameter();
    	for (int j = 0; j < name.length; j++) {
    		System.out.println(name[j]);
    		System.out.println(para[j]);
    	}
        
    }
    

	

    
	public void getTargetSets(){
		
		TargetSetResultObj result = queryHelper.getTargetSets(authObj);
		if (!result.isSuccess()) {
			
			String errMsg = result.getError();
			System.out.println(errMsg);
		}
		TargetSetObj targetset = new TargetSetObj();
		targetset = result.getTargetSetData(0);
		System.out.println(targetset.getSetName());
//		return result;
		
	}
    
	
	
}